{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="bs-example" data-example-id="table-within-panel">
            <div class="panel panel-default" style="margin-top: 20px">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <div>
                        <a href="{% url 'file' project_id=request.tracer.project.id %}">
                            <i class="fa fa-home" aria-hidden="true"></i> 文件库
                        </a>
                        {% for row in breadcrumb %}
                            <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ row.id }}">
                                <i class="fa fa-caret-right" aria-hidden="true"></i>
                                <span>{{ row.name }}</span>
                            </a>
                        {% endfor %}

                    </div>
                    <div class="function">
                        <div class="btn btn-primary btn-xs upload" style="position:relative;">
                            <div><i class="fa fa-upload" aria-hidden="true"></i>上传文件
                                <input type="file" multiple name="uploadFile" id="uploadFile">
                            </div>
                        </div>
                        <a href="" class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal"
                           data-whatever="新建文件夹">
                            <i class="fa fa-plus-circle" aria-hidden="true"></i>新建文件夹
                        </a>
                    </div>
                </div>

                <table class="table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>文件大小</th>
                        <th>更新者</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="rowList">
                    {% for item in file_obj_list %}
                        <tr>
                            <td>
                                {% if item.file_type == 1 %}
                                    <i class="fa fa-file" aria-hidden="true"></i>
                                    {{ item.name }}
                                {% else %}
                                    <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ item.id }}">
                                        <i class="fa fa-folder" aria-hidden="true"></i>
                                        {{ item.name }}
                                    </a>
                                {% endif %}

                            </td>
                            <td>
                                {% if item.file_type == 1 %}
                                    {{ item.file_size }}
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td>{{ item.update_user.username }}</td>
                            <td>{{ item.update_time }}</td>
                            <td>
                                {% if item.file_type == 2 %}

                                    <a class="btn btn-default btn-xs"
                                       data-toggle="modal"
                                       data-target="#addModal"
                                       data-name="{{ item.name }}"
                                       data-fid="{{ item.id }}"
                                       data-whatever="修改文件夹">
                                        <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                    </a>
                                {% else %}
                                    <a href="{% url 'file_download' project_id=request.tracer.project.id file_id=item.id %}"
                                       class="btn btn-default btn-xs">
                                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                    </a>
                                {% endif %}
                                <a class="btn btn-danger btn-xs"
                                   data-toggle="modal"
                                   data-target="#delModal"
                                   data-fid="{{ item.id }}"
                                   data-whatever="删除文件夹">
                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                </a>
                            </td>
                        </tr>
                    {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="modal fade" id="addModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <form method="post" id="addForm" novalidate>
                        {% csrf_token %}
                        <input type="text" class="hide" name="fid" id="fid">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg"></span>
                            </div>
                        {% endfor %}

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button type="button" class="btn btn-primary" id="btnSubmit">确 定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>是否要确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有的文件都会被删除。
                </p>
                <p style="text-align: right;">
                    <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                    <button id="btnDelete" type="button" class="btn btn-danger btn-sm" s="2">确 定</button>
                </p>
            </div>
        </div>
    </div>

    <!--进度条-->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i>上传进度
            </div>
            <table class="table">
                <tbody id="progressList">

                </tbody>
            </table>
        </div>
    </div>

    <!--进度条模版-->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    <!--显示上传文件结果列表模版-->
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>

                    <a class="btn btn-default btn-xs download" href="">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>

                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>

{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'file' project_id=request.tracer.project.id %}";
        var FILE_DELETE_URL = "{% url 'file_delete' project_id=request.tracer.project.id %}";
        var COS_CREDENTIAL = "{% url 'cos_credential' project_id=request.tracer.project.id %}";
        var FILE_POST = "{% url 'file_post' project_id=request.tracer.project.id %}";
        var PARENT_ID = "{{ current_folder.id }}";

        $(function () {
            AddModal();         // 初始化模态对话框
            bindModalSubmit();  // 添加文件夹
            bindDeleteSubmit(); // 删除文件夹
            bindUploadFile();   // 上传文件
        });

        function bindUploadFile() {
            // 获取临时凭证（获取一次5分钟）

            $('#uploadFile').change(function () {
                $('#progressList').empty();
                var filelist = $(this)[0].files;
                // 获取本次要上传的文件的名称和大小
                var checkfileslist = [];
                $.each(filelist, function (index, fileObject) {
                    checkfileslist.push({'name': fileObject.name, 'size': fileObject.size});
                });

                // 把这些数据发送到django后台：django后台进行容量的校验，如果没问题则返回临时凭证，否则返回错误信息
                var cos_credential = new COS({
                    // getAuthorization 必选参数
                    getAuthorization: function (options, callback) {
                        // 向django 后台发送请求，获取临时凭证
                        // $.ajax.get({type:"GET"})
                        //向后台发送上传的文件数据（大小、名称） JSON.stringify(checkfileslist)
                        $.post(COS_CREDENTIAL, JSON.stringify(checkfileslist), function (res) {
                            if (res.status) {
                                var credentials = res.data && res.data.credentials;
                                if (!res.data || !credentials) return console.error('credentials invalid');
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                                    StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
                                    ExpiredTime: res.data.expiredTime, // 时间戳，单位秒，如：1580000000
                                });
                                // 授权成功后显示进度条
                                $('#uploadProgress').removeClass('hide');
                            } else {
                                alert(res.error);
                            }

                        });

                    }
                });

                $.each(filelist, function (index, fileObject) {
                    var fileName = fileObject.name;
                    // 文件大小
                    var fileSize = fileObject.size;
                    // cos 中的文件名
                    var key = (new Date()).getTime() + "_" + fileName;

                    // 获取模版
                    var tr = $('#progressTemplate').find('tr').clone();
                    // 模版头部加入文件名
                    tr.find('.name').text(fileName);
                    // 将克隆的内容加到进度条显示
                    $('#progressList').append(tr);

                    // console.log(fileObject.name);
                    // 上传文件(异步）
                    cos_credential.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}',
                        Region: '{{ request.tracer.project.region }}',
                        Key: key,
                        Body: fileObject,  // 上传文件对象
                        onProgress: function (progressData) {
                            // console.log("文件上传进度--->", fileName, JSON.stringify(progressData));
                            // 得到文件上传百分比（进度）
                            var percent = progressData.percent * 100 + "%";
                            // 填入进度条百分比
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                        }

                    }, function (err, data) {
                        console.log(err || data);
                        if (data && data.statusCode === 200) {
                            // 上传成功，将本次上传的文件提交到后台
                            // 当前文件上传成功
                            $.post(FILE_POST, {
                                name: fileName,
                                key: key,
                                file_size: fileSize,
                                parent: PARENT_ID,
                                etag: data.ETag,
                                file_path: data.Location,
                            }, function (res) {
                                var newTpl = $('#rowTpl').find('tr').clone();
                                // 将后台返回的数据加载到模版表格中
                                newTpl.find('.name').text(res.data.name);
                                newTpl.find('.file_size').text((res.data.file_size / 1024).toFixed(2) + 'K');
                                newTpl.find('.username').text(res.data.username);
                                newTpl.find('.datetime').text(res.data.datetime);
                                newTpl.find('.download').attr('href',res.data.download_url);
                                newTpl.find('.delete').attr('data-fid', res.data.id);
                                // 将用户上传的文件显示到页面表格中
                                $('#rowList').append(newTpl);
                                // 上传成功后隐藏进度条
                                $('#progressList').remove();
                            })
                        } else {
                            tr.find('.progress-error').text("上传失败");
                        }
                    });

                });

            });
        }

        function bindDeleteSubmit() {
            $('#btnDelete').click(function () {
                // 向后台发送要删除的行数据的id
                $.ajax({
                    url: FILE_DELETE_URL,
                    type: "GET",
                    data: {fid: $(this).attr('fid')},
                    success: function (res) {
                        if (res.status) {
                            console.log(fid);
                            location.reload();
                        }
                    }
                })
            })
        }

        function AddModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var recipient = button.data('whatever');  // 获取 '#addModal' 相关属性
                var name = button.data('name');
                var fid = button.data('fid');
                var modal = $(this);
                modal.find('.modal-title').text(recipient);

                if (fid) {
                    // 编辑
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid);
                } else {
                    // 新建
                    modal.find('.error-msg').empty();
                    $('#addForm')[0].reset();
                }


            });
            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var fid = button.data('fid');
                $('#btnDelete').attr('fid', fid);

            })

        }

        function bindModalSubmit() {
            $('#btnSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: "POST",
                    data: $('#addForm').serialize(),
                    dataType: 'JSON',
                    success: function (res) {
                        if (res.status) {
                            location.reload();
                        } else {
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0]);
                            })
                        }
                    }
                })
            })
        }
    </script>
{% endblock %}